
const express = require('express')
const { User } = require('../models/index')
const app = express()
const router = express.Router({
    mergeParams: true
})
const SECRET = 'to love'

const jwt = require('jsonwebtoken')
app.use(express.json())
// 用户查询
router.get('/api/users', async (req, res) => {
    const users = await User.find()
    res.send(users)
})

router.post('/api/delUser', async (req, res) => {
    const Users = await User.deleteMany()
    res.send(Users)
})

// 用户注册
router.post('/api/register', async (req, res) => {
    const user = await User.create({
        username: req.body.username,
        password: req.body.password,
        region: req.body.region,
        sex: req.body.sex,
    })
    res.send({
        code: 200,
        message: "success"
    })
    // return res
})


// 用户登录验证
router.post('/api/login', async (req, res) => {
    const user = await User.findOne({
        username: req.body.username
    })


    // 用户验证
    if (!user) {
        return res.send({
            code: 301,
            message: '用户不存在'
        })
    }
    //密码验证
    const isPwdVaild = require('bcrypt').compareSync(
        req.body.password,
        user.password
    )
    // console.log(isPwdVaild)
    if (!isPwdVaild) {
        return res.send({
            code: 302,
            message: '密码错误'
        })
    }

    const token = jwt.sign({
        id: String(user._id)
    }, SECRET)

    // 最后返回
    res.send({
        code: 200,
        data: {
            user,
            token
        },
        message: "success"
    })
})


const auth = async (req, res, next) => {
    const raw = String(req.headers.authorization).split(' ').pop()
    const { id } = jwt.verify(raw, SECRET)
    req.user = await User.findById(id)
    next()
}
//用户信息获取
router.get('/api/profile', auth, (req, res) => {

    res.send(req.user)

}
)
module.exports = router